package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServicelmpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO report(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
//       dateList = begin-end期间日期集合，包含bigin，end
        List<Double> dateList2 = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginDate = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",beginDate);
            map.put("end",endDate);
            map.put("status", Orders.COMPLETED);
            Double getreport = orderMapper.getreport(map);
            getreport = getreport==null?0.0:getreport;
            dateList2.add(getreport);
        }
        String join = StringUtils.join(dateList, ",");
        String join1 = StringUtils.join(dateList2, ",");
        TurnoverReportVO tr = new TurnoverReportVO();
        tr.setDateList(join);
        tr.setTurnoverList(join1);
        return tr;
    }

    @Override
    public UserReportVO userStatustics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> addUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginDate = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(date,LocalTime.MAX);
            Integer addUser = userMapper.getUserReport(beginDate,endDate);
            addUserList.add(addUser);
            Integer totalUser = userMapper.getUserReport(null,endDate);
            totalUserList.add(totalUser);
        }

        String dateListJoin = StringUtils.join(dateList, ",");
        String addUserListJoin = StringUtils.join(addUserList, ",");
        String totalUserListJoin = StringUtils.join(totalUserList, ",");
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(dateListJoin);
        userReportVO.setNewUserList(addUserListJoin);
        userReportVO.setTotalUserList(totalUserListJoin);
        return userReportVO;
    }

    @Override
    public OrderReportVO ordersReport(LocalDate begin, LocalDate end) {

        List<LocalDate>dateList = new ArrayList<>();//日期集合
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer>orderList = new ArrayList<>();//每日订单集合
        List<Integer>ordersList = new ArrayList<>();//每日有效订单集合

        for (LocalDate date : dateList) {
            LocalDateTime beginDate = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(date,LocalTime.MAX);
            Integer ordercount = orderMapper.getorderDay(beginDate,endDate);
            orderList.add(ordercount);
            Integer orderscount = orderMapper.getordersDay(beginDate,endDate);
            ordersList.add(orderscount);
        }
        Integer totalOrderCount = orderMapper.getorderDay(null,null);  //订单总数
        Integer validOrderCount = orderMapper.getordersDay(null,null);  //有效订单总数
        Double ok = validOrderCount*1.0/totalOrderCount;  //订单完成率

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(ordersList,","));
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setOrderCompletionRate(ok);
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10Report(LocalDate begin, LocalDate end) {
        LocalDateTime beginDate = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDate = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTO = orderMapper.top10(beginDate,endDate);

        List<String> nameList = goodsSalesDTO.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameJoin = StringUtils.join(nameList, ",");
        List<Integer> numberList = goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberJoin = StringUtils.join(numberList, ",");

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameJoin);
        salesTop10ReportVO.setNumberList(numberJoin);
        return salesTop10ReportVO;
    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime beginDateTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(endDate, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginDateTime, endDateTime);

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {

            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间:"+beginDate+"至"+endDate);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
